Step 27: Test Bookmark Model
Update .env
file as follows:
DB_URI="mongodb+srv://bookmark-api-admin:<password>@bookmark-api.btuoger.mongodb.net/dev?retryWrites=true&w=majority"
DB_TEST_URI="mongodb+srv://bookmark-api-admin:<password>@bookmark-api.btuoger.mongodb.net/test?retryWrites=true&w=majority"
Notice the only difference between the DB_URI
and DB_TEST_URI
is the name of the database: dev
vs. test
There is a fundamental issue with how I decided to use a test database! My test database is in the MongoDB Atlas cluster. It is fine if I’m the only developer using this database. However, if I was part of a team, we should have not used a shared test database! It is a better practice if you use a test database that is local to your development environment.
Here is the plan: we will connect mongoose client to DB_TEST_URI
when we test. Update the tests/model/Bookmark.test.js
file as follows:
import { expect, test } from "vitest";
import Bookmark from "../../src/model/Bookmark.js";
import { faker } from "@faker-js/faker";
import * as db from "../../src/data/db.js";
import * as dotenv from "dotenv";
dotenv.config();
test("test constructor", async () => {
db.connect(process.env.DB_TEST_URI);
const title = faker.lorem.sentence();
const url = faker.internet.url();
const bookmark = await Bookmark.create({ title, url });
expect(bookmark.title).toBe(title);
expect(bookmark.url).toBe(url);
expect(bookmark.id).toBeDefined();
await Bookmark.deleteMany({});
});
Notice the use of dotenv
library. This library is what dotenv-cli
uses under the hood to read your environment variables from the .env
file. To put dotenv
library in action, we must call dotenv.config();
.
Notice in the test, we connect to the (test) database before testing, and delete all the test artifacts (i.e., Bookmark.deleteMany({});
) once the test is over (so it would not contaminate other tests).
Run this test and make sure it passes! Notice the “Connect to MongoDB!” message!
Save and commit all changes.